package com.gkj.shiro.realm;

import com.gkj.blog.business.enums.UserStatusEnum;
import com.gkj.blog.business.service.ResourcesService;
import com.gkj.blog.business.service.UserService;
import com.gkj.blog.business.vo.entity.Resources;
import com.gkj.blog.business.vo.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class CustomRealm extends AuthorizingRealm {

        @Autowired
        private UserService userService;
        @Autowired
        private ResourcesService resourcesService;

        @Override
        @Autowired
        public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
            super.setCredentialsMatcher(credentialsMatcher);
        }

         /**
         * 提供账户信息返回认证信息（用户的角色信息集合）
         *
         */
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
            //获取用户的输入的账号.
            String username = (String) token.getPrincipal();

            User user = userService.getUserByUsername(username);
            if (user == null) {
                throw new UnknownAccountException("账号不存在！");
            }
            if (user.getStatus() != null && UserStatusEnum.DISABLE.getCode().equals(user.getStatus())) {
                throw new LockedAccountException("帐号已被锁定，禁止登录！");
            }

            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                    user,
                    user.getPassword(),
                    ByteSource.Util.bytes(username),
                    getName()
            );
            return authenticationInfo;
        }

        /**
         * 权限认证，为当前登录的Subject授予角色和权限（角色的权限信息集合）
         */
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            List<Resources> resourcesList = resourcesService.listUserResources(user.getId());
            // 权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            if (!CollectionUtils.isEmpty(resourcesList)) {
                for (Resources resources : resourcesList) {
                    if (!StringUtils.isEmpty(resources.getUrl()) && !StringUtils.isEmpty(resources.getPermission())) {
                        String permission = resources.getPermission();
                        info.addStringPermission(permission);
                    }
                }
            }
            return info;
        }
}
